package com.fvision.camera.http;

import android.util.Log;

import com.fvision.camera.appupgrade.UpgradeManager;
import com.fvision.camera.utils.LogUtils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

import static android.content.ContentValues.TAG;

/**
 * Created by mayn on 2018/1/4.
 */

public class HttpRequest {
    static String baseUrl = "http://www.huiying616.com/watch/index.php?r=api";
    static String updateApk = "/package/check-update&";
    static String sanctionUrl = "/package/get-sanction&";
    static RequestIFace mLintener;
    static SanctionIFace mSanctionIFace;
    public static void requestGet(HashMap<String, String> paramsMap,RequestIFace lintener) {
        mLintener = lintener;
        try {
 //           String baseUrl = "http://apicloud.mob.com/v1/mobile/address/query?";
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String requestUrl = baseUrl + updateApk +tempParams.toString();
            LogUtils.d("requestUrl "+requestUrl);
            // 新建一个URL对象
            URL url = new URL(requestUrl);
            // 打开一个HttpURLConnection连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 设置连接主机超时时间
            urlConn.setConnectTimeout(5 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(5 * 1000);
            // 设置是否使用缓存  默认是true
            urlConn.setUseCaches(true);
            // 设置为Post请求
            urlConn.setRequestMethod("GET");
            //urlConn设置请求头信息
            //设置请求中的媒体类型信息。
            urlConn.setRequestProperty("Content-Type", "application/json");
            //设置客户端与服务连接类型
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // 开始连接
            urlConn.connect();
            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                // 获取返回的数据
                String result = streamToString(urlConn.getInputStream());
                Log.e("zoulequan", "Get方式请求成功，result--->");
                JSONObject json = new JSONObject(result);
                boolean status = json.getBoolean("status");
                JSONObject data = json.getJSONObject("data");
                if(status){
                    int version_code = data.getInt("version_code");
                    String version = data.getString("version");
                    String app_desc = data.getString("app_desc");
                    String path = data.getString("path");
                    LogUtils.d(" status "+status+" version_code "+version_code+" version "+version+" app_desc "+app_desc +" path "+path);
                    if(mLintener!=null){
                        mLintener.onSuccess(version_code,path,app_desc,version);
                    }
//                    UpgradeManager.getInstance().update(version_code,path,app_desc,version);
                }else {
                    int code = data.getInt("code");
                    String error = data.getString("message");
                    if(mLintener!=null){
                        mLintener.onFail(code,error);
                    }
                }

            } else {
                if(mLintener!=null){
                    mLintener.onFail(-1,"get request fail");
                }
                Log.e("zoulequan", "Get方式请求失败");
            }
            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            if(mLintener!=null){
                mLintener.onFail(50,e.toString());
            }
            Log.e(TAG, e.toString());
        }
    }

    public static void requestSanction(HashMap<String, String> paramsMap,SanctionIFace lintener) {
        mSanctionIFace = lintener;
        try {
            //           String baseUrl = "http://apicloud.mob.com/v1/mobile/address/query?";
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String requestUrl = baseUrl + sanctionUrl +tempParams.toString();
            LogUtils.d("requestUrl "+requestUrl);
            // 新建一个URL对象
            URL url = new URL(requestUrl);
            // 打开一个HttpURLConnection连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 设置连接主机超时时间
            urlConn.setConnectTimeout(5 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(5 * 1000);
            // 设置是否使用缓存  默认是true
            urlConn.setUseCaches(true);
            // 设置为Post请求
            urlConn.setRequestMethod("GET");
            //urlConn设置请求头信息
            //设置请求中的媒体类型信息。
            urlConn.setRequestProperty("Content-Type", "application/json");
            //设置客户端与服务连接类型
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // 开始连接
            urlConn.connect();
            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                // 获取返回的数据
                String result = streamToString(urlConn.getInputStream());
                LogUtils.e("zoulequan", "制裁请求成功，result--->" + result);
                JSONObject json = new JSONObject(result);
                boolean status = json.getBoolean("status");
                JSONObject data = json.getJSONObject("data");
                if(status){
                    int is_sanction = data.getInt("is_sanction");
                    if(mSanctionIFace!=null){
                        mSanctionIFace.onSuccess(is_sanction == 1);
                    }
//                    UpgradeManager.getInstance().update(version_code,path,app_desc,version);
                }else {
                    int code = data.getInt("code");
                    String error = data.getString("message");
                    if(mSanctionIFace!=null){
                        mSanctionIFace.onFail(code,error);
                    }
                }

            } else {
                if(mSanctionIFace!=null){
                    mSanctionIFace.onFail(-1,"get request fail");
                }
                Log.e("zoulequan", "Get方式请求失败");
            }
            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            if(mSanctionIFace!=null){
                mSanctionIFace.onFail(50,e.toString());
            }
            Log.e(TAG, e.toString());
        }
    }

    public static void javaHttpGet(HashMap<String, String> paramsMap) {
        String baseUrl = "http://apicloud.mob.com/v1/mobile/address/query?";
        StringBuilder tempParams = new StringBuilder();
        int pos = 0;
        for (String key : paramsMap.keySet()) {
            if (pos > 0) {
                tempParams.append("&");
            }
            try {
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            pos++;
        }
        String requestUrl = baseUrl + tempParams.toString();
        URL pathUrl;
        try {
            //创建一个URL对象
            pathUrl = new URL(requestUrl);
            HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();  //打开一个HttpURLConnection连接
            urlConnect.setConnectTimeout(10000);  // 设置连接超时时间
            urlConnect.connect();

            //输入流读取字节，再将它们转换成字符.得到读取的内容
            InputStreamReader in = new InputStreamReader(urlConnect.getInputStream());
            //BufferedReader:接受Reader对象作为参数，并对其添加字符缓冲器，使用readline()方法可以读取一行
            BufferedReader buffer = new BufferedReader(in);
            String inputLine = null;
            String resultData = null;
            while ((inputLine=buffer.readLine()) !=null) {
                //利用循环来读取数据
                resultData +=inputLine;
            }
            LogUtils.d("resultData "+resultData);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void requestPost(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/getUsers";
            //合成参数
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key,  URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String params =tempParams.toString();
            // 请求的参数转换为byte数组
            byte[] postData = params.getBytes();
            // 新建一个URL对象
            URL url = new URL(baseUrl);
            // 打开一个HttpURLConnection连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间
            urlConn.setConnectTimeout(5 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(5 * 1000);
            // Post请求必须设置允许输出 默认false
            urlConn.setDoOutput(true);
            //设置请求允许输入 默认是true
            urlConn.setDoInput(true);
            // Post请求不能使用缓存
            urlConn.setUseCaches(false);
            // 设置为Post请求
            urlConn.setRequestMethod("POST");
            //设置本次连接是否自动处理重定向
            urlConn.setInstanceFollowRedirects(true);
            // 配置请求Content-Type
            urlConn.setRequestProperty("Content-Type", "application/json");
            // 开始连接
            urlConn.connect();
            // 发送请求参数
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                // 获取返回的数据
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "Post方式请求成功，result--->");
            } else {
                Log.e(TAG, "Post方式请求失败");
            }
            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    /**
     * 将输入流转换成字符串
     *
     * @param is 从网络获取的输入流
     * @return
     */
    public static String streamToString(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return null;
        }
    }

    private void downloadFile(String fileUrl){
        try {
            // 新建一个URL对象
            URL url = new URL(fileUrl);
            // 打开一个HttpURLConnection连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 设置连接主机超时时间
            urlConn.setConnectTimeout(5 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(5 * 1000);
            // 设置是否使用缓存  默认是true
            urlConn.setUseCaches(true);
            // 设置为Post请求
            urlConn.setRequestMethod("GET");
            //urlConn设置请求头信息
            //设置请求中的媒体类型信息。
            urlConn.setRequestProperty("Content-Type", "application/json");
            //设置客户端与服务连接类型
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // 开始连接
            urlConn.connect();
            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                String filePath="";
                File  descFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(descFile);;
                byte[] buffer = new byte[1024];
                int len;
                InputStream inputStream = urlConn.getInputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    // 写到本地
                    fos.write(buffer, 0, len);
                }
            } else {
                Log.e(TAG, "文件下载失败");
            }
            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    public interface RequestIFace{
        void onSuccess(int version_code,String path,String app_desc,String version);
        void onFail(int errorCode,String error);
    }

    public interface SanctionIFace{
        void onSuccess(boolean isSanction);
        void onFail(int errorCode,String error);
    }
}
